#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

from os import path
import logging

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp

import core_settings
from core.models import CoreUser
from core.utils import reset_calendar_url, reset_token

# gdata
from gdata.service import RequestError

class BaseRequestHandler(webapp.RequestHandler):

    def init_fixtures(self, user):
        self.bad_init = False
        coreuser = CoreUser.all().filter('user =', user).get()

        if coreuser is None:
            self.bad_init = True
            return self.redirect(self.request.host_url + '/core/register/', True)

        # Ask for a token if the user hasn't already got it
        if not coreuser.token:            
            logging.info("Coreuser has not token")
            reset_token(self)
        else:
            if not coreuser.id_calendar:
                logging.info("Coreuser has not id calendar")
                try:
                    reset_calendar_url(coreuser, 'textlocutor')
                except RequestError, e:
                    if e[0]['status'] == 403:
                        return {'error': "You are not a Google Calendar user, if you don't get an account, you won't be able to receive the messages. Get an account <a href='https://www.google.com/accounts/Login?service=cl'>here</a>"}



    def generate(self, template_values, template_file):
        self.response.out.write(template.render(
                path.join(core_settings.TEMPLATE_DIR, template_file), 
                template_values))
